<template>
  <div class="createPost-container">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      class="form-container"
    >
      <div class="createPost-main-container">
        <el-row gutter="80">
          <el-col :span="24">
            <div class="postInfo-container">
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="announcementName"
                  label-width="180px"
                  label="通知标题："
                >
                  <el-input
                    v-model="postForm.announcementName"
                    :maxlength="100"
                    name="name"
                    required
                    :disabled="isView"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label-width="180px"
                    prop="announcementType"
                    label="通知类型："
                  >
                    <el-select
                      v-model="postForm.announcementType"
                      :remote-method="getTypeList"
                      filterable
                      remote
                      placeholder="请选择通知类型"
                      :loading="loading"
                      required
                      :disabled="isView"
                    >
                      <el-option
                        v-for="item in typeListOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.label"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    style="margin-bottom: 40px"
                    prop="announcementDate"
                    label-width="180px"
                    label="通知日期："
                  >
                    <el-date-picker
                      v-model="postForm.announcementDate"
                      type="date"
                      placeholder="请选择日期"
                      disabled
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-form-item
                  prop="announcementContent"
                  label="通知内容："
                  label-width="180px"
                  style="margin-bottom: 30px"
                >
                  <Tinymce
                    v-if="!isView"
                    ref="editor"
                    v-model="postForm.announcementContent"
                    :height="400"
                    :disabled="isView"
                  />

                  <div class="text-content-container"><p v-if="isView" v-html="postForm.announcementContent"></p></div>
                </el-form-item>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    style="margin-bottom: 40px"
                    prop="announcementStatus"
                    label-width="180px"
                    label="状态："
                  >
                    <template>
                      <el-radio
                        v-model="postForm.announcementStatus"
                        label="普通"
                        :disabled="isView"
                        >普通</el-radio
                      >
                      <el-radio
                        v-model="postForm.announcementStatus"
                        label="置顶"
                        :disabled="isView"
                        >置顶</el-radio
                      >
                    </template>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label-width="180px"
                    prop="announcementCreatorId"
                    label="通知创建者："
                  >
                    <el-select
                      v-model="postForm.announcementCreatorId"
                      :remote-method="getUserList"
                      filterable
                      remote
                      placeholder="请选择创建者"
                      :loading="loading"
                      @change="changeUser"
                      required
                      disabled
                    >
                      <el-option
                        v-for="item in userListOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-form-item label-width="180px" label="文件：">
                  <el-upload
                    class="file-uploader"
                    action="http://localhost:3001/api/announcements/upload"
                    :limit="1"
                    :on-preview="handlePreview"
                    :before-remove="beforeRemove"
                    :on-exceed="handleExceed"
                    :on-success="handleSuccess"
                    :file-list="fileList"
                  >
                    <el-button size="small" type="primary" v-if="!isView">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip" v-if="!isView">
                      .docs 文件小于500kb
                    </div>
                  </el-upload>
                </el-form-item>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </div>

      <el-button
        v-show="!isView"
        v-loading="loading"
        style="margin-left: 230px; width: 100px"
        type="success"
        @click="submitForm"
      >
        保存
      </el-button>
    </el-form>
  </div>
</template>

<script>
import Tinymce from "@/components/Tinymce";
import announcementTypes from "@/data/announcementTypes";
import {
  fetchAnnouncementById,
  createAnnouncement,
  updateAnnouncement,
} from "@/api/announcement";
import { fetchUserList } from "@/api/user";
import { generateNewDate } from '@/utils/date';
import { mapGetters } from 'vuex'

const defaultForm = {
  announcementName: "", // 通知标题
  announcementType: "", // 通知类型
  announcementContent: "", // 通知内容
  announcementAttachmentPath: "", // 通知附件
  announcementAttachmentName: "", // 通知附件名字
  announcementDate: generateNewDate(), // 通知日期
  announcementCreatorId: "", // 通知创建者ID
  announcementCreatorName: "", // 通知创建者姓名
  announcementStatus: "普通", // 仪器状态： 置顶，普通
  id: undefined,
};

export default {
  name: "AnnouncementDetail",
  components: { Tinymce },
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    isView: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("此为必填项"));
      } else {
        callback();
      }
    };

    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userList: [],
      userListOptions: [],
      fileList: [],
      typeListOptions: announcementTypes,
      rules: {
        announcementName: [{ required: true, validator: validateRequire }],
        announcementType: [{ required: true, validator: validateRequire }],
        announcementContent: [{ required: true, validator: validateRequire }],
        announcementDate: [{ required: true, validator: validateRequire }],
        announcementOwnerId: [{ required: true, validator: validateRequire }],
        announcementStatus: [{ required: true, validator: validateRequire }],
        announcementCreatorId: [{ required: true, validator: validateRequire }],
      },
    };
  },
  computed: {
    ...mapGetters(["id", "name"])
  },
  created() {
    this.getUsers();
    if (this.isEdit || this.isView) {
      const id = this.$route.params && this.$route.params.id;
      this.fetchData(id);
    } else {
      this.postForm.announcementCreatorId = this.id;
      this.postForm.announcementCreatorName = this.name;
    }
  },
  methods: {
    getUsers() {
      this.listLoading = true;
      fetchUserList().then((res) => {
        this.userList = res.data.map((item) => {
          return { label: item.userName, value: item.id };
        });
        this.userListOptions = this.userList;

        this.listLoading = false;
      });
    },
    getUserList(query) {
      if (query !== "") {
        this.loading = true;

        this.userListOptions = userList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.userListOptions = userList;
      }
    },
    changeUser(val) {
      this.postForm.announcementCreatorName = this.userList.find((item) => {
        return item.value === val;
      }).label;
    },
    getTypeList(query) {
      if (query !== "") {
        this.loading = true;
        this.loading = false;
        this.typeListOptions = announcementTypes.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.typeListOptions = announcementTypes;
      }
    },
    handlePreview(file) {
      let a = document.createElement('a');
      let event = new MouseEvent('click');
      a.download = file.name;
      a.href = file.response? `http://localhost:3001/${file.response.srcurl}` : file.url;
      a.dispatchEvent(event);
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `文件数量限制为1, 您选择了 ${files.length} 个文件。`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`删除 ${file.name} ?`);
    },
    async handleSuccess(res, file) {
      if (res.status === "1") return this.$message.error(res.message);
        this.postForm.announcementAttachmentPath = `http://localhost:3001/${res.srcurl}`;
        this.postForm.announcementAttachmentName = file.name;
    },
    fetchData(id) {
      fetchAnnouncementById(id)
        .then((res) => {
          this.postForm = res.data[0];
          this.fileList = this.postForm.announcementAttachmentName
              ? [
                  {
                    name: this.postForm.announcementAttachmentName,
                    url: this.postForm.announcementAttachmentPath,
                  },
                ]
              : [];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    submitForm() {
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.postForm.id) {
            updateAnnouncement(this.postForm.id, this.postForm)
              .then((res) => {
                if (res.data) {
                  this.$router.push("/announcement/list");
                  this.$message({
                    title: "成功",
                    message: "通知信息更新成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "通知信息更新失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          } else {
            createAnnouncement(this.postForm)
              .then((res) => {
                if (res.data) {
                  this.$router.push("/announcement/list");

                  this.$message({
                    title: "成功",
                    message: "通知创建成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "通知创建失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          }
        } else {
          console.log("通知信息保存失败");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }
}

.identity-container {
  margin-top: 50px;
}

.text-content-container{
  border: 1px solid #c5c5c5;
  padding: 0 1rem;
}
</style>
